﻿using System;
using System.Data.Linq;
using System.IO;
using System.Linq;
using System.Net;

namespace Registration.Twitter
{
    public static class TwitterLoader
    {
        public static void LoadIntoDatabaseFromFile(string file)
        {
            LoadIntoDatabase(File.ReadAllText(file));
        }

        public static void LoadIntoDatabaseFromTwitter(string hashtag)
        {
            int count = 100;
            int page = 1;
            while (count == 100)
            {
                count = LoadIntoDatabaseFromTwitter(hashtag, page++);
                Console.WriteLine("loaded "+ count);
            }
        }

        private static string GetLastTweetId(string hashtag)
        {
            using (var d = new Database())
            {
                var id =  (from t in d.Tweets
                        where t.Tweet1.Contains(hashtag)
                        orderby t.TwitterID descending
                        select t.TwitterID).FirstOrDefault();
                Console.WriteLine("id=" + id);
                return id;
            }
        }

        public static int LoadIntoDatabaseFromTwitter(string hashtag, int page)
        {
            var url = "http://search.twitter.com/search.json?q=%23" + hashtag + "&since_id=0" + 
                      "&rpp=100&page="+page;
            Console.WriteLine(url);
            string txt = null;
            using (var r = WebRequest.Create(url).GetResponse())
            {
                Stream res = r.GetResponseStream();
                txt = new StreamReader(res).ReadToEnd();
            }
            //Debug.Print(txt);
            return LoadIntoDatabase(txt);
        }

        private static int LoadIntoDatabase(string text)
        {
            int tweetCount;
            using (Database d = new Database())
            {
                var all = TwitterParser.Load(text);
                Save(all.Item2, d.Authors);
                Save(all.Item1, d.Tweets);
                Save(all.Item3, d.Mentions);
                d.SubmitChanges();
                tweetCount = all.Item1.Count();
            }
            return tweetCount;
        }

        private static void Save<T>(T[] items, Table<T> table) where T : class
        {
            foreach (var t in items)
            {
                table.InsertOnSubmit(t);
            }
        }

        public static void CleanDatabase()
        {
            using (Database d = new Database())
            {
            d.Tweets.DeleteAllOnSubmit(d.Tweets);
            d.Mentions.DeleteAllOnSubmit(d.Mentions);
            d.Authors.DeleteAllOnSubmit(d.Authors);
            d.SubmitChanges();
            }
        }
    }
}